﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cofe.Core;
using Cofe.Core.Utils;

namespace Cofe.Core.Filter
{
    /// <summary>
    /// ILookupFilter that takes a Cofe.Core.SearchOptionEx, 
    /// to return whether continue to lookup a directory.
    /// This OptionFilter is handled by RootEntryFilter.
    /// </summary>
    [EntryFilter("subdir")]
    public class SearchOptionOptionFilter : OptionFilterBase, ISearchOptionOptionFilter
    {
        public SearchOptionOptionFilter(
            SearchOption searchOption = SearchOption.TopDirectoryOnly,
            string id = "subdir")
            : base(searchOption.ToString(), id)
        {
            _searchOption = searchOption;
        }

        private static SearchOption parseSearchOption(string searchOptionString)
        {
            switch (searchOptionString.ToLower())
            {
                case "all":
                    return SearchOption.AllDirectoriesAndFileBasedFS;
                case "true":
                    return SearchOption.AllDirectories;
                case "false":
                    return SearchOption.TopDirectoryOnly;
            }

            SearchOption searchOption;

            if (EnumUtils<SearchOption>.EnumTryParse(searchOptionString,
                out searchOption))
                return searchOption;

            return SearchOption.TopDirectoryOnly;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchOptionString">TopDirectoryOnly, AllDirectories or AllDirectoriesAndFileBasedFS</param>
        public SearchOptionOptionFilter(string searchOptionString, string id = "subdir")
            : this(parseSearchOption(searchOptionString), id)
        {
        }

        private SearchOption _searchOption;
        public SearchOption SearchOption { get { return _searchOption; } }

        public bool ContinueLookup(ICofeDirectoryInfo directory)
        {
            switch (_searchOption)
            {
                case SearchOption.TopDirectoryOnly: return false;
                case SearchOption.AllDirectoriesAndFileBasedFS: return true;
                case SearchOption.AllDirectories: return !directory.IsFileBasedFS;
                default: throw new NotSupportedException("SearchOption");
            }
        }
    }
}
